package com.tianji.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.tianji.StragyHttp.utils.SessionUtil;
import com.tianji.StragyHttp.utils.UserSession;
import com.tianji.common.Result;
import com.tianji.exception.BizException;
import com.tianji.upload.enum1.BucketNameEnum;
import com.tianji.upload.param.S3SdkPutParam;
import com.tianji.upload.param.S3SdkPutResult;
import com.tianji.upload.utils.S3SdkUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequestMapping("/public")
@Api(tags = "公共-通用接口")
public class UploadOSSController {

    @Value("${jd.oss.uploadImagePathPrefix}")
    private String uploadImagePathPrefix;

    private final static String UPLOAD_IMAGE_SUFFIX = "jpeg,jpg,png";

    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST")
    @PostMapping("/uploadImage")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        UserSession user = SessionUtil.getUser();
        String pictureName = null;
        try {
            // 文件原始名
            String originalFileName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("\\") + 1);
            // 文件类型
            String fileNameSuffix = FileUtil.getSuffix(originalFileName).toLowerCase();
            if (!UPLOAD_IMAGE_SUFFIX.contains(fileNameSuffix)) {
                String message = StrUtil.format("仅支持图片类型：{} 当前图片类型为：{}", UPLOAD_IMAGE_SUFFIX, fileNameSuffix);
                throw new RuntimeException(message);
            }
            log.info("[上传图片] 文件名：{}，文件类型：{}，文件大小：{}", originalFileName, fileNameSuffix, file.getSize());
            //文件新路径
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //图片存储时全部采用uuid
            pictureName = user.getUserId() + "_" + fileName + "." + fileNameSuffix;
            // 上传到阿里云
            S3SdkPutParam putParam = new S3SdkPutParam(file.getInputStream(), BucketNameEnum.YEION_PUBLIC, pictureName, file.getSize());
            S3SdkPutResult putResult = S3SdkUtil.put(putParam);
            if (!putResult.getSuccess()) {
                log.error("上传文件到oss失败,文件名为：{}，", pictureName);
            }
            String url = uploadImagePathPrefix + BucketNameEnum.YEION_PUBLIC.getBucket() + "/" + pictureName;
            return Result.success("上传图片成功", url);
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            throw new BizException( "上传文件到oss失败,文件名为" + pictureName);
        }
    }
}
